# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import UserError
from odoo.tools import float_is_zero, float_compare


class ApproveFlow(models.Model):
    """'
    单据审核流程,每个单据一个审核流程
    """
    _name = 'approve.flow'
    _order = 'sequence'

    res_model = fields.Char()
    res_id = fields.Integer()
    sequence = fields.Integer()
    user_id = fields.Many2one('res.users')
    approve_type = fields.Selection([
        ('normal', '签核'),
        ('info', '通知'),
        ('add', '會簽')
    ],default='normal')

    amount = fields.Float()
    remark = fields.Char(string='備註')

    _sql_constraints = [
        ('unique_seq', 'unique (sequence,res_model,res_id)', '序號必須唯一!'),
    ]

    # @api.multi
    # def write(self, vals):
    #     if not self.user_has_groups('account.group_account_user') or (not self.user_has_groups(
    #             'account.group_account_manager')) or (not self.user_has_groups('account.group_account_invoice')):
    #         raise UserError('只有財務人員可以修改簽核流程')
    #
    #     return super(ApproveFlow, self).write(vals)

class ApprovalActionWizard(models.TransientModel):
    """
        没有审核流的审核动作
    """
    _name = "to.approval.action.wizard"

    res_model = fields.Char()
    remark = fields.Text(string=u'備註')

    def submit(self):
        context = dict(self._context or {})

        active_ids = context.get('active_ids', [])
        model_ids = self.env[self.res_model].browse(active_ids)
        model_ids.action_submit()

    def reject(self):
        if not self.remark:
            raise UserError(u'簽核意見必填')
        context = dict(self._context or {})
        active_ids = context.get('active_ids', [])
        model_ids = self.env[self.res_model].browse(active_ids)
        remark = self.remark if self.remark else ''
        model_ids.action_reject(remark=remark)

    def approve(self):
        context = dict(self._context or {})
        active_ids = context.get('active_ids', [])
        model_ids = self.env[self.res_model].browse(active_ids)
        remark = self.remark if self.remark else ''
        model_ids.action_approve(remark=remark)

    def retract(self):
        context = dict(self._context or {})
        active_ids = context.get('active_ids', [])
        model_ids = self.env[self.res_model].browse(active_ids)
        remark = self.remark if self.remark else ''
        model_ids.action_cancel_approval(remark=remark)

    def add_auditor(self):
        context = dict(self._context or {})
        active_ids = context.get('active_ids', [])
        return {
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'res_model': 'add.auditor.wizard',
            'target': 'new',
            'context': {'default_res_id': active_ids[0],
                        'default_res_model': self.res_model}

        }

